<?php

namespace app\api\model;

use app\admin\event\SystemLog;
use app\api\model\Goods\Speci\Brand;
use app\api\model\Goods\Speci\Category;
use app\api\model\Goods\Speci\Color;
use app\api\model\Goods\Speci\Material;
use app\api\model\Goods\Speci\Season;
use app\api\model\Goods\Speci\Size;
use app\api\model\Goods\Speci\Style;
use app\api\model\Goods\Speci\Unit;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Db;

class ShopModel extends Base {

    protected $table = 'jxc_shop';
    protected $auto = ['status' => 0];

    protected static function init() {
        self::observe(SystemLog::class);
    }

    public function getSeasonAttr($value) {
        return Season::find($value)['name'];
    }

    public function getMaterialAttr($value) {
        return Material::find($value)['name'];
    }

    public function getUnitAttr($value) {
        return Unit::find($value)['name'];
    }

    public function getCategoryAttr($value) {
        return Category::find($value)['name'];
    }

    public function getBrandAttr($value) {
        return Brand::find($value)['name'];
    }

    public function getSizeAttr($value) {
        return Size::find($value)['name'];
    }

    public function getStyleAttr($value) {
        return Style::find($value)['name'];
    }

    public function getColorAttr($value) {
        return Color::find($value)['name'];
    }

    public function commodity() {
        return $this->belongsTo(Commodity::class, 'commodity_id');
    }

    public function product() {
        return $this->belongsTo(Product::class, 'product_id');
    }

    /**
     * 获取订单状态名称
     * @param type $status
     */
    public function getOrderStatus($status) {
        $status_name = '';
        switch ($status) {
            case 0:
                $status_name = '待付款';
                break;
            case 1:
                $status_name = '待确认';
                break;
            case 2:
                $status_name = '待发货';
                break;
            case 3:
                $status_name = '待收货';
                break;
            case 4:
                $status_name = '已完成';
                break;
            case 5:
                $status_name = '已撤销';
                break;
            default:
                break;
        }
        return $status_name;
    }

    /**
     * 获取配送方式名称
     * @param type $send
     */
    public function getSendName($send) {
        $send_name = '';
        switch ($send) {
            case 1:
                $send_name = '自提';
                break;
            case 2:
                $send_name = '送车';
                break;
            case 3:
                $send_name = '送指定点';
                break;
            case 4:
                $send_name = '电子面单';
                break;
            case 5:
                $send_name = '发物流';
                break;
            default:
                break;
        }
        return $send_name;
    }

    public function getUpperGoods($id) {
        $current = $this->where(['product_id' => $id])->select();
        if ($current->count() > 0) {
            return 2;
        } else {
            $product = Product::with('commodity')->find($id);
//            $list = $this->getOne('goods', '*', ['id' => $id]);
            $data['name'] = $product['commodity']['name'];
            $data['item'] = $product['commodity']['item'];
            $data['goods_code'] = $product['commodity']['goods_code'];
//            $data['status'] = 0;
            $data['color'] = $product->getData()['color'];
            $data['size'] = $product->getData()['size'];
            $data['unit'] = $product->commodity->getData()['unit'];
            $data['material'] = $product->commodity->getData()['material'];
            $data['season'] = $product->commodity->getData()['season'];
            $data['style'] = $product->getData()['style'];
            $data['brand'] = $product->commodity->getData()['brand'];
            $data['category'] = $product->commodity->getData()['category'];
            $data['sex'] = $product->commodity->getData()['sex'];
            $data['year'] = $product->commodity->getData()['year'];
            $data['sort'] = $product['commodity']['sort'];
            $data['commodity_id'] = $product['commodity']['id'];
            $data['product_id'] = $id;
            return $this->save($data);
        }
    }

    /**
     * @param $id
     * @param Commodity $commodity
     * @return array|\PDOStatement|string|Model
     */
    public function getUpperGoodsInfo($id) {
        try {
            return $this->findOrFail($id);
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $id
     * @param $data
     * @return mixed
     */
    public function getUpperGoodsEdit($id, $data) {
        try {
            $current = $this->findOrFail($id);
            if ($current) {
                return $current->save($data);
            } else {
                return false;
            }
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getBatchUpper($data) {
        foreach ($data as $k => $v) {
            $current = $this->getOne('shop', '*', ['pid' => $v]);
            if (empty($current)) {
                $list = $this->getOne('goods', '*', ['id' => $v]);
                $data['name'] = $list['name'];
                $data['item'] = $list['item'];
                $data['goods_code'] = $list['goods_code'];
                $data['status'] = 0;
                $data['color'] = $list['color'];
                $data['size'] = $list['size'];
                $data['unit'] = $list['unit'];
                $data['material'] = $list['material'];
                $data['season'] = $list['season'];
                $data['style'] = $list['style'];
                $data['brand'] = $list['brand'];
                $data['category'] = $list['category'];
                $data['sex'] = $list['sex'];
                $data['year'] = $list['year'];
                $data['sort'] = $list['sort'];
                $data['pid'] = $v;
                $arr = $this->getAdd('shop', $data);
            }
        }
        return $arr;
    }

    public function getBatchLower($data) {
        foreach ($data as $k => $v) {
            $current = $this->getOne('shop', '*', ['pid' => $v]);
            if (!empty($current)) {
                $this->getSetField('shop', ['id' => $current['id']], ['status' => 1]);
            }
        }
        return 1;
    }

    /**
     * 商城---订单列表
     * @param type $page
     * @param type $size
     * @param type $where
     * @return type
     */
    public function getOrderList($page, $size, $where) {
        $limit = ($page - 1) * $size;
        $sql = 'select o.*,m.shop_phone,m.shop_name,m.status as member_status from jxc_order as o left join jxc_member as m on o.member = m.id '
                . 'where ' . $where . ' limit ' . $limit . ',' . $size;
        $list = Db::query($sql);
        if (!empty($list)) {
            foreach ($list as &$val) {
                $val['create_date'] = date('Y-m-d', $val['create_time']);
                //状态
                $val['status_name'] = $this->getOrderStatus($val['status']);
                $val['status2'] = $val['status'] + 37;
                //配送方式
                $val['delivery_name'] = $this->getSendName($val['delivery']);
                //付款方式
                $val['payment_name'] = '微信支付';
                //关联状态
                $val['member_status_name'] = $val['member_status'] ? '已关联' : '未关联';
            }
            unset($val);
        }
        //总条数
        $sql_c = 'select o.*,m.shop_phone,m.shop_name,m.status as member_status from jxc_order as o left join jxc_member as m on o.member = m.id '
                . 'where ' . $where;
        $list_c = Db::query($sql_c);
        $total = count($list_c);
        //总页码
        $last_page = intval(ceil($total / $size));
        return array(
            'current_page' => $page, //当前页
            'per_page' => $size, //每页条数
            'last_page' => $last_page, //总页数
            'total' => $total, //总条数
            'data' => $list, //数据数组
        );
    }

    /**
     * 获取订单信息
     * @param type $id
     * @return type
     */
    public function getOrderInfo($id) {
        $list = $this->getOne('order', '*', ['id' => $id]);
        //格式化数据
        $list['create_date'] = date('Y-m-d', $list['create_time']);
        $list['status_name'] = $this->getOrderStatus($list['status']);
        $list['payment_name'] = '微信支付';
        //已收款
        $list['pay_money'] = $list['status'] ? $list['money'] : '0.00';
        //配送方式
        $list['delivery_name'] = $this->getSendName($list['delivery']);
        //会员信息
        $member_info = db('member')->where(['id' => $list['member']])->find();
        $list['member_name'] = !empty($member_info) ? $member_info['shop_name'] : '';
        $list['member_phone'] = !empty($member_info) ? $member_info['shop_phone'] : '';
        $list['member_status'] = !empty($member_info) ? $member_info['status'] : 0;
        if ($member_info['status']) {
            $user_info = db('user')->where(['id' => $member_info['relation_id']])->field('name,phone')->find();
            $list['user_info'] = $user_info['name'] . '+' . $user_info['phone'];
        } else {
            $list['user_info'] = '';
        }
        $list['goods'] = $this->getselectList('order_relation', '*', ['pid' => $list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $dan = $this->getOne('product', 'commodity_id,color,size', ['id' => $v['goods_id']]);
            $goods = $this->getOne('commodity', 'name,item,goods_code,retail_price,unit', ['id' => $dan['commodity_id']]);
            $list['goods'][$k]['name'] = $goods['name'];
            $list['goods'][$k]['item'] = $goods['item'];
            $list['goods'][$k]['retail_price'] = $goods['retail_price'];
            $list['goods'][$k]['goods_code'] = $goods['goods_code'];
            $list['goods'][$k]['color'] = $this->getValue('color3', ['id' => $dan['color']], 'name');
            $list['goods'][$k]['size'] = $this->getValue('color3', ['id' => $dan['size']], 'name');
            $list['goods'][$k]['unit'] = $this->getValue('color1', ['id' => $goods['unit']], 'name');
        }
        return $list;
    }

    /**
     * 销售单撒销
     * @param type $id
     * @return int
     */
    public function getOrderRevoke($id) {
        $list = $this->getOne('turn_sale', '*', ['order_id' => $id]);
        if (!empty($list)) {
            return 2;
        } else {
            $this->getSetField('order', ['id' => $id], ['status' => 5]);
            return 1;
        }
    }

    /**
     * 转销售单
     * @param type $id
     * @return int
     */
    public function getOrderTurn($id) {
        $list = $this->getOne('order', '*', ['id' => $id]);
        $list['goods'] = $this->getselectList('order_relation', '*', ['pid' => $list['id']]);
        $arr['kid'] = $list['member'];
        $arr['create_time'] = time();
        $arr['number'] = 'jxc' . time();
        $arr['set_account'] = $list['payment'];
        $arr['payment'] = $list['money'];
        $arr['maker'] = 1;
        $arr['type1'] = 1;
        $sale_id = $this->getAdd('sale', $arr);
        foreach ($list['goods'] as $k => $v) {
            $data['goods_id'] = $v['goods_id'];
            $data['put_number'] = $v['num'];
            $data['pid'] = $sale_id;
            $data['discount'] = $v['discount'];
            $data['discount_price'] = $v['discount_price'];
            $data['money'] = $v['money'];
            $data['discount_money'] = $v['discount_money'];
            $this->getAdd('salerelation', $data);
        }
        $rel['sale_id'] = $sale_id;
        $rel['order_id'] = $id;
        $rel['status'] = 1;
        $this->getAdd('turn_sale', $rel);
        //同步订单
        db('order')->where(['id' => $id])->update(['sale_id' => $sale_id]);
        return 1;
    }

    /**
     * 改价
     * @param type $option
     * @return int
     */
    public function getOrderRevision($option) {
        $id = $option['id']; //订单id
        $fare = $option['fare']; //运费
        $money = 0; //订单金额
        foreach ($option['goods'] as &$val) {
            db('order_relation')->where(['id' => $val['id']])->update([
                'discount' => $val['discount'], //折扣
                'discount_price' => $val['discount_price'], //折后价
                'discount_money' => bcsub($val['money'], $val['discount_price'], 2),
            ]);
            $money = bcadd($money, $val['discount_price'], 2);
        }
        unset($val);
        $res = db('order')->where(['id' => $id])->update([
            'money' => $money,
            'fare' => $fare
        ]);
        if ($res) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * 会员列表
     * @param type $data
     * @return type
     */
    public function getMemberList($page, $size, $where) {
        $list = db('member')->where($where)->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                $val['status_name'] = !empty($val['status']) ? '已关联' : '未关联';
                $val['kh_phone'] = '';
                $val['kh_tel'] = '';
                $val['kh_status'] = '';
                $val['kh_status_name'] = '';
                $val['kh_email'] = '';
                $val['kh_address'] = '';
                $val['kh_remark'] = '';
                if (!empty($val['relation_id'])) {//查询关联客户信息
                    $user_info = db('user')->where(['id' => $val['relation_id']])->field('phone,tel,status,email,address,remark')->find();
                    $val['kh_phone'] = $user_info['phone'];
                    $val['kh_tel'] = $user_info['tel'];
                    $val['kh_status'] = $user_info['status'];
                    $val['kh_status_name'] = $user_info['status'] == 1 ? '启用' : '禁用';
                    $val['kh_email'] = $user_info['email'];
                    $val['kh_address'] = $user_info['address'];
                    $val['kh_remark'] = $user_info['remark'];
                }
            }
        }
        return $list;
    }

    /**
     * 获取会员信息
     * @param type $id
     * @return type
     */
    public function getMemberInfo($id) {
        $list = $this->getOne('member', '*', ['id' => $id]);
        if ($list['status'] == 1) {
            $user = $this->getOne('user', 'name,phone,category,tel,email,province,city,area,address,status,remark', ['id' => $list['relation_id']]);
            $list['kh_name'] = $user['name'];
            $list['kh_phone'] = $user['phone'];
            $list['kh_tel'] = $user['tel'];
            $list['kh_email'] = $user['email'];
            $list['kh_address'] = $user['province'] . $user['city'] . $user['area'] . $user['address'];
            $list['kh_status'] = $user['status'];
            $list['kh_status_name'] = $user['status'] == 1 ? '启用' : '禁用';
            $list['kh_remark'] = $user['remark'];
            //客户分类
            $cate_name = db('customer_category')->where(['id' => $user['category']])->field('name')->find();
            $list['cate_name'] = !empty($cate_name) ? $cate_name['name'] : '';
        }
        return $list;
    }

    /**
     * 关联客户
     * @param type $member_id
     * @param type $user_id
     * @return int
     */
    public function getMemberRelation($member_id, $user_id) {
        $member = db('member')->where(['id' => $member_id])->find();
        if ($member['status'] == 0) {//未关联
            //开启事务
            Db::startTrans();
            $res1 = db('member')->where(['id' => $member_id])->update([
                'status' => 1,
                'relation_id' => $user_id
            ]);
            $res2 = db('user')->where(['id' => $user_id])->update([
                'member' => 1,
                'member_phone' => $member['shop_phone'],
                'm_nickname' => $member['shop_name'],
                'we_nickname' => $member['nick_name'],
            ]);
            if ($res1 !== FALSE && $res2 != FALSE) {
                //提交事务
                Db::commit();
                return TRUE;
            } else {
                //事务回滚
                Db::rollback();
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    /**
     * 解除会员关联
     * @param type $id
     * @return int
     */
    public function getMemberMove($id) {
        $list = $this->getOne('member', '*', ['id' => $id]);
        if ($list['status'] == 1) {
            $this->getSetField('member', ['id' => $id], ['status' => 0, 'relation_id' => 0]);
            db('user')->where(['id' => $list['relation_id']])->update(['member' => 0, 'member_phone' => '', 'm_nickname' => '']);
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * 编辑店铺信息
     * @param type $id
     * @param type $data
     * @return type
     */
    public function getStoreStateEdit($id, $data) {
        $list = $this->getEdit('store_state', ['id' => $id], $data);
        return $list;
    }

    /**
     * 店铺信息
     * @param type $id
     * @return type
     */
    public function getStoreStateInfo($id) {
        //店铺信息
        $detail = db('store_state')->where(['id' => $id])->find();
        //订单统计
        $cnt = db('order')->where('status > 0')->field('count(if(status=1,1,null)) as confirm_num,count(if(status=4,1,null)) as finish_num,count(if(status>1,1,null)) as turn_num')->find();
        //一周订单数
        $start_time = 0; //strtotime(date('Y-m-d 00:00:00',strtotime('-1 week')));
        $week = db('order')->where('create_time > ' . $start_time . ' and create_time <' . time())->field('count(1) as num,FROM_UNIXTIME(`create_time`,"%Y-%m-%d") as date')->group('date')->select();
        $week_date = $week_num = [];
        if (!empty($week)) {
            $week_date = array_column($week, 'date');
            $week_num = array_column($week, 'num');
        }
        return array(
            'detail' => $detail,
            'cnt' => $cnt,
            'week' => array(
                'date' => $week_date,
                'num' => $week_num
            )
        );
    }

    /**
     * 店铺设置---首页轮播图
     * @return type
     */
    public function getBannerList() {
        $list = db('banner')->order('sort', 'desc')->select();
        if (!empty($list)) {
            foreach ($list as &$val) {
                $val['images'] = '//' . $val['images'];
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 店铺设置---新增轮播图
     * @param type $data
     * @return type
     */
    public function getBannerAdd($data) {
        $data['ctime'] = time();
        //获取排序值
        $sort = db('banner')->max('sort');
        $data['sort'] = $sort + 1;
        return db('banner')->insert($data);
    }

    /**
     * 店铺设置---编辑轮播图
     * @param type $id
     * @param type $data
     * @return type
     */
    public function getBannerEdit($id, $data) {
        $list = $this->getEdit('banner', ['id' => $id], $data);
        return $list;
    }

    /**
     * 店铺设置---删除轮播图
     * @param type $id
     * @param type $data
     * @return type
     */
    public function getBannerDel($id) {
        $list = $this->getDel('banner', ['id' => $id]);
        return $list;
    }

    /**
     * 商城上架商品列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getUpperListNew($page, $size, $where) {
        $limit = ($page - 1) * $size;
        $sql = 'select c.id,c.name,c.item,c.purchase_price,c.trade_price,c.retail_price,c.goods_code,c.brand,c.category,c.material,c.season,c.year,c.sex,c.sort,'
                . 's.id as shop_id,s.status as sale_status,s.tag from jxc_commodity as c left join jxc_shop as s on c.id = s.commodity_id where ' . $where . ' limit ' . $limit . ',' . $size;
        $list = Db::query($sql);
        if (!empty($list)) {
            foreach ($list as &$val) {
                //上架状态
                $val['sale_status_name'] = is_null($val['sale_status']) ? '未上架' : ($val['sale_status'] ? '已下架' : '已上架');
                $val['material_name'] = $this->getMaterialAttr($val['material']);
                $val['season_name'] = $this->getSeasonAttr($val['season']);
                $product_info = db('product')->where(['commodity_id' => $val['id']])->field('style')->find();
                $style = !empty($product_info) ? $product_info['style'] : 0;
                $val['style_name'] = $style ? $this->getStyleAttr($style) : '';
                $val['category_name'] = $style ? $this->getCategoryAttr($val['category']) : '';
                $val['sex_name'] = !empty($val['sex']) ? ($val['sex'] == 1 ? '女款' : '通款') : '男款';
            }
            unset($val);
        }
        //总条数
        $sql_c = 'select c.id,c.name,c.item,c.purchase_price,c.trade_price,c.retail_price,c.goods_code,c.brand,c.category,c.material,c.season,c.year,c.sex,c.sort,'
                . 's.id as shop_id,s.status as sale_status,s.tag from jxc_commodity as c left join jxc_shop as s on c.id = s.commodity_id where ' . $where;
        $list_c = Db::query($sql_c);
        $total = count($list_c);
        //总页码
        $last_page = intval(ceil($total / $size));
        return array(
            'current_page' => $page, //当前页
            'per_page' => $size, //每页条数
            'last_page' => $last_page, //总页数
            'total' => $total, //总条数
            'data' => $list, //数据数组
        );
    }

    /**
     * 批量上架商品
     * @param type $id_list
     */
    public function batchRackingGoods($id_list) {
        $err_id = [];
        foreach ($id_list as &$val) {
            $shop_info = db('shop')->where(['commodity_id' => $val])->find(); //上架商品信息
            if (empty($shop_info)) {//上架商品表没数据就上架，有就不用重复上架
                $com_info = db('commodity')->where(['id' => $val])->find(); //商品信息
                $product_list = db('product')->where(['commodity_id' => $val])->select();
                if (!empty($product_list)) {
                    foreach ($product_list as $vv) {
                        db('shop')->insert([
                            'name' => $com_info['name'],
                            'item' => $com_info['item'],
                            'goods_code' => $com_info['goods_code'],
                            'status' => 0,
                            'color' => $vv['color'],
                            'size' => $vv['size'],
                            'unit' => $com_info['unit'],
                            'material' => $com_info['material'],
                            'season' => $com_info['season'],
                            'style' => $vv['style'],
                            'brand' => $com_info['brand'],
                            'category' => $com_info['category'],
                            'sex' => $com_info['sex'],
                            'price' => $com_info['retail_price'],
                            'year' => $com_info['year'],
                            'sort' => $com_info['sort'],
                            'product_id' => $vv['id'],
                            'commodity_id' => $val,
                            'ctime' => time()
                        ]);
                    }
                }
            } else {
                $err_id[] = $val;
            }
        }
        unset($val);
        return ['exist_com' => $err_id];
    }

    /**
     * 批量下架商品
     * @param type $id_list
     */
    public function batchSoldoutGoods($id_list) {
        $err_id = [];
        foreach ($id_list as &$val) {
            $res = db('shop')->where(['id' => $val])->update([
                'status' => 1,
                'utime' => time()
            ]);
            if (empty($res)) {
                $err_id[] = $val;
            }
        }
        unset($val);
        return ['err_list' => $err_id];
    }

    /**
     * 搜索客户列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getSearchUserList($page, $size, $where) {
        $list = db('user')->where($where)->field('id,name,phone')->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                $val['name_phone'] = $val['name'] . '+' . $val['phone'];
            }
            unset($val);
        }
        return $list;
    }

    /**
     * banner图排序
     * @param type $id
     * @param type $sort
     */
    public function editBannerSort($id, $sort) {
        $eg = $sort == 'asc' ? '>' : '<';
        $sort = db('banner')->where(['id' => $id])->column('sort');
        $last_sort = db('banner')->where('sort', $eg, current($sort))->field('id,sort')->find();
        if (!empty($last_sort)) {
            $res1 = db('banner')->where(['id' => $id])->update(['sort' => $last_sort['sort']]);
            $res2 = db('banner')->where(['id' => $last_sort['id']])->update(['sort' => current($sort)]);
            if ($res1 && $res2) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
        return FALSE;
    }

    /**
     * 获取上架商品列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getOnshopnList($page, $size, $where) {
        $list = db('shop')->where('status = 0 and ' . $where)->field('id,name,item,goods_code,brand,category,tag,type')->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                //品牌
                $val['brand_name'] = $this->getBrandAttr($val['brand']);
                //分类
                $val['category_name'] = $this->getCategoryAttr($val['category']);
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 新增运费模板
     * @param type $data
     */
    public function addFreight($data) {
        $data['ctime'] = time();
        if ($data['is_df']) {
            //先取消已有默认的模板
            db('freight')->where(['is_df' => 1])->update(['is_df' => 0]);
        }
        return db('freight')->insert($data);
    }

    /**
     * 编辑运费模板
     * @param type $id
     * @param type $data
     */
    public function editFreight($id, $data) {
        $info = db('freight')->where(['id' => $id])->field('is_free,goods_list,area_list')->find();
        if ($info['is_free']) {
            return FALSE;
        }
        if ($data['is_df']) {
            //先取消已有默认的模板
            db('freight')->where(['is_df' => 1])->update(['is_df' => 0]);
        }
        //已选地区
        if ($info['area_list']) {
            $area_list = $info['area_list'] . ',' . $data['area_list'];
            $area_arr = array_unique(explode(',', $area_list));
            $data['area_list'] = implode(',', $area_arr);
        }
        return db('freight')->where(['id' => $id])->update($data);
    }

    /**
     * 删除运费模板
     * @param type $id
     */
    public function delFreight($id) {
        $freight = db('freight')->where(['id' => $id])->find();
        if (1 == $freight['is_free']) {
            return FALSE;
        }
        return db('freight')->where(['id' => $id])->delete();
    }

    /**
     * 获取运费模板列表
     */
    public function getFreightList() {
        $list = db('freight')->order('is_free', 'asc')->order('id', 'desc')->select();
        if (!empty($list)) {
            foreach ($list as &$val) {
                $val['is_df_bool'] = boolval($val['is_df']);
                $val['is_free_bool'] = boolval($val['is_free']);
                $goods_id = explode(',', $val['goods_list']);
                //商品信息
                $goods_list = db('shop')->whereIn('id', $goods_id)->field('id,name,item,goods_code,brand,category,tag,type')->select();
                if (!empty($goods_list)) {
                    foreach ($goods_list as $k => $v) {
                        $goods_list[$k]['brand_name'] = $this->getBrandAttr($v['brand']);
                        $goods_list[$k]['category_name'] = $this->getBrandAttr($v['brand']);
                    }
                }
                $val['goods_list'] = $goods_list;
                $val['goods_num'] = count($goods_list);
                //省市名称
                $area_list = db('area')->whereIn('id', explode(',', $val['area_list']))->column('name');
                $val['area_list_name'] = implode(',', $area_list);
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 批量设置商品标签
     * @param type $tag
     * @param type $goods_list
     */
    public function batchShopTag($tag, $goods_list) {
        if (!empty($goods_list)) {
            db('shop')->whereIn('id', $goods_list)->update(['tag' => $tag]);
        }
        $num = db('shop')->where(['tag' => $tag])->count();
        return ['num' => $num];
    }

    /**
     * 修改系统配置
     * @param type $param
     */
    public function editSystemConfig($name, $key, $value) {
        $config = db('system')->where(['key' => $key])->find();
        if (empty($config)) {
            $res = db('system')->insert([
                'name' => $name,
                'key' => $key,
                'value' => json_encode($value),
                'ctime' => time()
            ]);
        } else {
            $res = db('system')->where(['key' => $key])->update(['value' => json_encode($value)]);
        }
        return $res;
    }

    /**
     * 获取系统配置值
     * @param type $key
     */
    public function getSystemConfig($key) {
        $config = db('system')->where(['key' => $key])->find();
        $value = [];
        if (!empty($config)) {
            $value = json_decode($config['value'], TRUE);
        }
        return $value;
    }

    /**
     * 获取上架商品积分规则
     */
    public function getShopRuleConfig() {
        //上架商品
        $shop_total = db('commodity')->count();
        $on_shop = db('shop')->where(['status' => 0])->group('commodity_id')->count();
        //销量价格
        $sale_price = $this->getSystemConfig('sale_price_show');
        //商品标签
        $tags_num = db('shop')->field('count(if(tag="精品",1,null)) as jp_num,count(if(tag="热卖",1,null)) as rm_num,count(if(tag="新品",1,null)) as xp_num')->find();
        //运费模板
        $freight = $this->getFreightList();
        if (!empty($freight)) {
            foreach ($freight as &$val) {
                $val['goods_num'] = count($val['goods_list']);
                //省市名称
                $area_list = db('area')->whereIn('id', explode(',', $val['area_list']))->column('name');
                $val['area_list_name'] = implode(',', $area_list);
            }
            unset($val);
        }
        //库存
        $repertory = $this->getSystemConfig('repertory_config');

        return array(
            'shop_onsale' => array(
                'onsalse' => $on_shop,
                'total' => $shop_total
            ),
            'sale_price' => $sale_price,
            'tags_num' => $tags_num,
            'freight' => $freight,
            'repertory' => $repertory
        );
    }

    /**
     * 批量设置商品运费模板
     * @param type $id
     * @param type $goods_id
     */
    public function batchShopFreight($id, $goods_id) {
        $info = db('freight')->where(['id' => $id])->field('is_free,goods_list,area_list')->find();
        //已选商品
        if (!empty($info['goods_list'])) {
            $goods_list = $info['goods_list'] . ',' . $goods_id;
            $goods_arr = array_unique(explode(',', $goods_list));
            $goods_id = implode(',', $goods_arr);
        }
        $res = db('freight')->where(['id' => $id])->update(['goods_list' => $goods_id]);
        if ($res !== FALSE) {
            if (!empty($goods_id)) {
                $goods_list = explode(',', $goods_id);
                db('shop')->whereIn('id', $goods_list)->update(['type' => $id]);
            } else {//应用至全部商品
                db('shop')->where('1=1')->update(['type' => $id]);
            }
        }
        $num = db('shop')->where(['type' => $id])->count();
        return ['num' => $num];
    }

    /**
     * 获取运费模板详情
     * @param type $id
     */
    public function getFreightInfo($id) {
        $data = db('freight')->where(['id' => $id])->find();
        $goods_id = explode(',', $data['goods_list']);
        //商品信息
        $goods_list = db('shop')->whereIn('id', $goods_id)->field('id,name,item,goods_code,brand,category,tag,type')->select();
        if (!empty($goods_list)) {
            foreach ($goods_list as $k => $v) {
                $goods_list[$k]['brand_name'] = $this->getBrandAttr($v['brand']);
                $goods_list[$k]['category_name'] = $this->getBrandAttr($v['brand']);
            }
        }
        $data['goods_list'] = $goods_list;
        $data['goods_num'] = count($goods_list);
        //省市名称
        $area_list = db('area')->whereIn('id', explode(',', $data['area_list']))->column('name');
        $data['area_list_name'] = implode(',', $area_list);
        return $data;
    }

    /**
     * 设置默认运费模板
     * @param type $id
     */
    public function setDefaultFreight($id) {
        //先取消已有默认的模板
        $res = db('freight')->where(['is_df' => 1])->update(['is_df' => 0]);
        if ($res !== FALSE) {
            //再设置
            db('freight')->where(['id' => $id])->update(['is_df' => 1]);
        }
        return $res;
    }

    /**
     * APP获取商城订单列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function appGetOrderList($page, $size, $where) {
        $list = db('order')->alias('o')->field('o.id,o.order_num,o.status,o.money,o.delivery,o.remark,o.create_time,m.shop_name')->join('member m', 'o.member = m.id', 'LEFT')->where($where)->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                $val['create_time'] = date('Y-m-d H:i', $val['create_time']);
                //状态名称
                $val['status_name'] = $this->getOrderStatus($val['status']);
                //相关活动
                $relation = db('order_relation')->where(['pid' => $val['id']])->field('coupon_id,seckil_id,discount_id')->select();
                $active_name = '';
                foreach ($relation as $v) {
                    if ($v['coupon_id']) {
                        $active_name = '优惠';
                    }
                    if ($v['seckil_id']) {
                        $active_name = '秒杀';
                    }
                    if ($v['discount_id']) {
                        $active_name = '折扣';
                    }
                }
                $val['active_name'] = $active_name;
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 领取会员卡
     * @param type $member_id
     */
    public function getMemberCard($member_id) {
        $info = db('member')->where(['id' => $member_id])->field('card_num')->find();
        if (!empty($info['card_num'])) {
            return FALSE;
        }
        $card_num = date('YmdHis');
        db('member')->where(['id' => $member_id])->update(['card_num' => $card_num, 'card_time' => time()]);
        return TRUE;
    }

    /**
     * 获取会员已领取优惠券列表
     * @param type $page
     * @param type $size
     * @param type $member_id
     */
    public function getCouponList($page, $size, $member_id) {
        $list = db('coupon_member')->alias('c')->field('c.id,c.status,c.order_id,p.name,p.condition,p.money,p.create_time,p.fail_time')->join('coupon p', 'c.coupon_id = p.id', 'LEFT')
                        ->where(['c.member_id' => $member_id])->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                $val['create_time'] = date('Y.m.d', $val['create_time']);
                $val['fail_time'] = date('Y.m.d', $val['fail_time']);
                //状态
                $status_name = '';
                if (0 == $val['status']) {//未使用
                    $status_name = '去使用';
                }
                if (1 == $val['status']) {//已使用
                    $status_name = '已使用';
                }
                if (2 == $val['status']) {//已过期
                    $status_name = '已过期';
                }
                $val['status_name'] = $status_name;
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 获取会员已领取优惠券列表
     * @param type $page
     * @param type $size
     * @param type $member_id
     */
    public function getUngetCouponList($page, $size, $member_id) {
        $id_list = db('coupon_member')->where(['member_id' => $member_id])->column('coupon_id');
        $id_list = array_unique($id_list);
        $list = db('coupon')->where(['status' => 2])->whereNotIn('id', $id_list)->field('id,name,condition,money,create_time,fail_time')->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                $val['create_time'] = date('Y.m.d', $val['create_time']);
                $val['fail_time'] = date('Y.m.d', $val['fail_time']);
                //状态
                $val['status_name'] = '去领取';
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 领取会员卡
     * @param type $id
     * @param type $member_id
     */
    public function collectCoupon($id, $member_id) {
        $log = db('coupon_member')->where(['coupon_id' => $id, 'member_id' => $member_id])->find();
        if (!empty($log)) {
            return FALSE;
        }
        db('coupon_member')->insert([
            'coupon_id' => $id,
            'member_id' => $member_id,
            'ctime' => time(),
        ]);
        return TRUE;
    }

    /**
     * 获取会员积分概况
     * @param type $member_id
     */
    public function getMemberIntegral($member_id) {
        $info = db('member')->where(['id' => $member_id])->field('integral')->find();
        $num = db('integral_logs')->where(['member_id' => $member_id])->field('sum(if(type=0,num,0)) as get_num,sum(if(type=1,num,0)) as used_num')->find();
        return array(
            'integral' => $info['integral'],
            'get_num' => $num['get_num'],
            'used_num' => $num['used_num']
        );
    }

    /**
     * 获取积分列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getIntegralList($page, $size, $where) {
        $list = db('integral_logs')->where($where)->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                switch ($val['type']) {
                    case 0:
                        $val['type_name'] = '购买商品获得积分';
                        $val['type_status'] = 0; //增加
                        $val['type_status_name'] = '增加';
                        break;
                    case 1:
                        $val['type_name'] = '消耗积分抵消费金额';
                        $val['type_status'] = 1; //减少
                        $val['type_status_name'] = '减少';
                        break;
                    case 2:
                        $val['type_name'] = '客户管理中修改积分';
                        if ($val['num'] > 0) {
                            $val['type_status'] = 0;
                            $val['type_status_name'] = '增加';
                        } else {
                            $val['type_status'] = 1;
                            $val['type_status_name'] = '减少';
                        }
                        break;
                }
                $val['ctime_date'] = date('Y-m-d H:i', $val['ctime']);
                //销售单id
                $order = db('order')->where(['id' => $val['order_id']])->field('sale_id')->find();
                $val['sale_id'] = !empty($order) ? $order['sale_id'] : 0;
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 获取积分明细列表
     * @param type $page
     * @param type $size
     * @param type $where
     */
    public function getIntegralDetailList($member_id, $page, $size, $where) {
        $list = db('integral_logs')->alias('l')->field('l.*,o.id as order_id,o.order_num,o.money,o.sale_id')->leftJoin('order o', 'l.order_id = o.id')->where($where)->limit($page, $size)->paginate($size)->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$val) {
                //名称
                $val['name'] = '销售单';
                $val['ctime_date'] = date('Y-m-d H:i', $val['ctime']);
                //积分
                $goods = db('order_relation')->where(['pid' => $val['order_id']])->column('goods_id');
                $score = 0;
                foreach($goods as $v){
                    $score += $this->getIntegral($member_id, $v, $val['money']);
                }
                $val['score'] = $score;
            }
            unset($val);
        }
        return $list;
    }

    /**
     * 根据会员id和单品id获取积分数量
     * @param type $member_id
     * @param type $goods_id
     */
    public function getIntegral($member_id, $goods_id, $money) {
        $score = 0;
        $rule_list = db('integral_rule')->where(['gain' => 0])->field('id,cid,goods,gain_tj,gain_jf')->select();
        if (!empty($rule_list)) {
            foreach ($rule_list as &$val) {
                $goods_arr = explode(',', $val['goods']);
                if (in_array($goods_id, $goods_arr)) {
                    $score = $money * $val['gain_jf'] / $val['gain_tj'];
                }
            }
            unset($val);
        }
        return $score;
    }

}
